import type { ConstructorOf, CreateMethodOf, PoolImpl, PoolObject } from "../declarations";

/**
 * - 作者: DoooReyn
 * - 日期: 2023.10.29
 * - 名称: Pool
 * - 描述: 对象池
 */
export class Pool<T extends PoolObject> implements PoolImpl<T> {
    /** 对象列表 */
    private __items: T[];

    /** 预加载数量 */
    private __preloads: number;

    /** 对象模板 */
    private __template: ConstructorOf<T> | CreateMethodOf<T> | null;

    /**
     * 构造
     * @param cls 对象类或对象创建方法
     * @param preloads 预加载数量
     */
    public constructor(cls: ConstructorOf<T> | CreateMethodOf<T>, preloads: number) {
        this.__template = cls;
        this.__preloads = preloads;
        this.__items = [];
        this.preload();
    }

    public get size() {
        return this.__items.length;
    }

    public preload() {
        for (let i = 0; i < this.__preloads; i++) {
            if (this.size < this.__preloads) {
                this.__items.push(this.create());
            }
        }
    }

    public create() {
        // @ts-ignore
        return new this.__template() as T;
    }

    public get(): T {
        const item: T = this.size > 0 ? this.__items.pop()! : this.create();
        item.use();
        return item;
    }

    public put(obj: T): void {
        if (this.__items.indexOf(obj) === -1) {
            obj.recycle();
            this.__items.push(obj);
        }
    }

    public clear(): void {
        this.__items.length = 0;
    }
}
